package com.qdsg.modulesihealsdk.deCard;

import static com.qdsg.modulesihealsdk.utils.SihealSdkConstant.CARD_NULL;

import android.app.Activity;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.decard.NDKMethod.BasicOper;
import com.decard.NDKMethod.DCReader;
import com.decard.driver.utils.HexDump;
import com.example.moduleutils.LogUtil;
import com.qdsg.modulesihealsdk.BuildConfig;
import com.qdsg.modulesihealsdk.utils.SihealSdkConstant;
import com.qdsg.modulesihealsdk.utils.StrUtils;

import java.io.UnsupportedEncodingException;

/**
 * @Description 德卡读卡器帮助类
 * @Author WuJianFeng
 * @Date 2022/11/21 15:36
 */
public class ReadCardUtils {
    private static int openDeviceError = 0;

    public static void initDevice(Context context, InitDeviceCallback initDeviceCallback){
        //usb模式需要调用此接口，打开之前必须确保已经获取到USB权限，返回值为设备句柄号。
        BasicOper.dc_AUSB_ReqPermission(context);
        //打开端口
        long devHandle= BasicOper.dc_open("LUSB", context, "", 0);

        if (devHandle < 0){
            openDeviceError++;
            if (openDeviceError > 5){
                initDeviceCallback.failed();
            }else {
                initDevice(context, initDeviceCallback);
            }
        }
        if (devHandle > 0) {
            openDeviceError = 0;
            Log.d("open", "dc_open success devHandle = $devHandle");

            //读社保卡需要调用此接口
            BasicOper.setInitParameter(2, null, 0);
            //usb链接需要调用此接口
            BasicOper.CreateAndroidContext(context);
            initDeviceCallback.success();

        }
    }

    /**
     * 身份证读取
     */
    public static void readIdCard(Activity activity, ReadCardUtilsCallback readCardUtilsCallback){
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try{
                    byte[] info = new byte[4096];
                    String result = null;
                    int resCard = DCReader.iReadIdentityCard(info);
                    if (resCard == 0) {
                        result  = new String(info,  "UTF-8").trim();
                    } else {
                        result  = new String(info, "GBK").trim();
                    }
                    if (result.equals(CARD_NULL)){
                        if (readCardUtilsCallback != null){
                            readCardUtilsCallback.nullCard();
                        }
                        return;
                    }
//                        吴xx            |男|汉族|19960729|xx省xx县xx镇xx村xx               |35xx2419xxxx290xxx|20140214|20240214|xx县公安局         |/9j/4AAQxxxxxxQAAAQABAAD/2wBDAAoHBwgHBgoICxxxxxxxxxxxEmKzcvJik0KSEiMEExNDk7Pj4+JS5ESUM8SDc9Pjv/2wBDAQoxxxxx7O|
                    // 得到数据
                    if (result.equals(SihealSdkConstant.DE_ERR)){
                        String finalResult = result;
                        initDevice(activity, new InitDeviceCallback() {
                            @Override
                            public void success() {
                                readIdCard(activity,readCardUtilsCallback);
                            }

                            @Override
                            public void failed() {
                                if (readCardUtilsCallback != null){
                                    readCardUtilsCallback.errMsg(finalResult);
                                }
                            }
                        });

                    }else {
                        if (readCardUtilsCallback != null){
                            readCardUtilsCallback.idCardData(StrUtils.parseIdentity(result));
                        }

                    }

                }catch(UnsupportedEncodingException e) {
                    if (readCardUtilsCallback != null){
                        readCardUtilsCallback.errMsg(e.getMessage());
                    }

                }
            }
        });
    }

    /**
     * 读取社保卡
     */
    public static void readSocialSecurityCard(Activity activity, ReadCardUtilsCallback readCardUtilsCallback){
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try{
                    byte[] info = new byte[4096];
                    String result = null;
                    int resInfo = DCReader.iReadPersonInfo(info);
                    result  = new String(info, "GBK").trim();

                    if (result.equals(CARD_NULL)){
                        if (readCardUtilsCallback != null){
                            readCardUtilsCallback.nullCard();
                        }
                        return;
                    }
                    if (result.equals(SihealSdkConstant.DE_ERR)){
                        String finalResult = result;
                        initDevice(activity, new InitDeviceCallback() {
                            @Override
                            public void success() {
                                readSocialSecurityCard(activity,readCardUtilsCallback);
                            }

                            @Override
                            public void failed() {

                                if (readCardUtilsCallback != null){
                                    readCardUtilsCallback.errMsg(finalResult);
                                }
                            }
                        });

                    }else {
                        if (readCardUtilsCallback != null){
                            readCardUtilsCallback.socialSecurityCardData(StrUtils.parseSocialSecurityCard(result));
                        }

                    }
                }catch(UnsupportedEncodingException e) {
                    Log.d("DCReader_Result_error", "" + e);
                    if (readCardUtilsCallback != null){
                        readCardUtilsCallback.errMsg(e.getMessage());
                    }
                }
            }
        });
    }


    /**
     * 扫描二维码
     */
    private static boolean startReadCard = true;
    public static void startReadCard(QRCodeCallback qrCodeCallback) {
        startReadCard = true;
        //开启二维码扫描
        String start_scan_2D = BasicOper.dc_Scan2DBarcodeStart(0x00);
        if (start_scan_2D.split("\\|")[0].equals("0000")) {
            new Thread(() -> {

                while (startReadCard){
                    try {
                        String scan_2D_info = BasicOper.dc_Scan2DBarcodeGetData();
                        //获取二维码扫描结果
                        if (scan_2D_info.split("\\|")[0].equals("0000")) {
                            try {
                                String data = new String(HexDump.hexStringToByteArray(scan_2D_info.split("\\|")[1]),"Gbk").trim();
                                qrCodeCallback.result(data);
                            } catch (UnsupportedEncodingException e) {
                                throw new RuntimeException(e);
                            }

                        }
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();

        }
    }


    public static void scanQRCodeStop(){
        startReadCard = false;
        BasicOper.dc_Scan2DBarcodeExit();
    }



}
